package codingInterview.leetcode.editor.cn;

//输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。 
//
// 
//
// 示例 1： 
//
// 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
//输出：[1,2,3,6,9,8,7,4,5]
// 
//
// 示例 2： 
//
// 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
//输出：[1,2,3,4,8,12,11,10,9,5,6,7]
// 
//
// 
//
// 限制： 
//
// 
// 0 <= matrix.length <= 100 
// 0 <= matrix[i].length <= 100 
// 
//
// 注意：本题与主站 54 题相同：https://leetcode-cn.com/problems/spiral-matrix/ 
// Related Topics 数组 矩阵 模拟 👍 369 👎 0

//Java：剑指 Offer 29 - 顺时针打印矩阵
public class ShunShiZhenDaYinJuZhenLcof {
    public static void main(String[] args) {
        Solution solution = new ShunShiZhenDaYinJuZhenLcof().new Solution();
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        private int[] res = new int[0];
        private int index = 0;

        public int[] spiralOrder(int[][] matrix) {

            if (matrix == null || matrix.length <= 0 || matrix[0].length <= 0) return res;
            int n = matrix.length, m = matrix[0].length;
            res = new int[n * m];
            for (int i = 0; i < (n + 1) / 2 && i < (m + 1) / 2; i++) {
                printARound(matrix, i, m, n);
            }
            return res;
        }
        /**
         *  (start,start) ——————————————
         *        |                     |
         *        |                     |
         *        ————————————————(endX,endY)
         *                                   (width,length)
         */
        private void printARound(int[][] matrix, int start, int length, int width) {
            int endY = length - start - 1;  //结束的y坐标
            int endX = width - start - 1; //结束的x坐标
//            System.out.println(start + " - " + endX + " - " + endY);
            //从左到右
            for (int i = start; i <= endY; i++) {
                res[index++] = matrix[start][i];
            }
            //从上到下
            if (start < endX) { //圈子超过1行
                for (int i = start + 1; i <= endX; i++) {
                    res[index++] = matrix[i][endY];
                }
            }
            // 从右到左
            if (start < endY && start < endX) { // 圈子超过一行一列
                for (int i = endY - 1; i >= start; i--) {
                    res[index++] = matrix[endX][i];
                }
            }
            // 从下到上
            if (start < endY && start < endX - 1) { // 圈子超过2行
                for (int i = endX - 1; i > start; i--) {
                    res[index++] = matrix[i][start];
                }
            }
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
